//tslint:disable
import { Component, OnInit, Input, OnDestroy, ChangeDetectorRef } from "@angular/core";

import { ActionSheetController, AlertController, Platform } from "@ionic/angular";
import { ModalController } from "@ionic/angular";

import { Subscription } from "rxjs";

import { MessageService } from "src/app/shared/service/message.service";

import { isNullOrUndefined } from 'util';

import { ActionSheetService, Modal, ModalService } from 'ng-zorro-antd-mobile';
import { EventService } from 'src/app/shared/service/event.service';
import { SharePageComponent } from 'src/app/coms/share-page/share-page.component';

import { RemarksContentComponent } from "../remarks-content/remarks-content.component";
import { ServiceModuleComponent } from '../service-module/service-module.component';
import { AppGlobalService } from "../../shared/service/app-global.service";
import { PageModalService } from "../../shared/service/page-modal-service";
import { HttpService } from "../../shared/service/http.service";
import { NewBusinessInfoModalComponent } from '../new-business-info-modal/new-business-info-modal.component';
import { ShareService } from 'src/app/shared/service/share.service';
import { ShareFormModalComponent } from "../share-form-modal/share-form-modal.component";
import { ImgSlidePage } from "../slides-imgage/img-slide.page";
import { NestedFormTagComponent } from "../nested-form-tag/nested-form-tag.component";
import { RecommendModalComponent } from "../recommend-modal/recommend-modal.component";
import { ModalFromCenterLeave, ModalFromCenterEnter } from "src/app/utils/transitions";
import { VideoImgPopupComponent } from "../video-img-popup/video-img-popup.component";
@Component({
  selector: 'app-info-audit-list',
  templateUrl: './info-audit-list.component.html',
  styleUrls: ['./info-audit-list.component.scss'],
})
export class InfoAuditListComponent implements OnInit {
  @Input() tagData: any;
  openInformation = false;
  openRemarks = false;
  icons = [];
  remarksText = "";
  remarksIcon: any;
  phoneArray = [];
  dataIndex: any;
  firstTextStyle: any = {};
  secondTagStyle: any = {};
  firstTagStyle: any = {};
  secondTestStyle: any = {};
  pageNo: any = 1;
  params: any;
  sessionId = localStorage.getItem("sessionId");
  // 声明订阅对象
  subscription: Subscription = null;
  emptyDataHint = "暂无数据";
  pageTotal: number;
  pageSize: number;
  showLoadMore = false;

  constructor(
    private appGlobalService: AppGlobalService,
    private pageModalService: PageModalService,
    private actionSheetCtrl: ActionSheetController,
    private actionSheet: ActionSheetService, // 必须有
    private alertController: AlertController,
    private eventService: EventService,
    private message: MessageService,
    private httpService: HttpService,
    private shareService: ShareService,
    private ref: ChangeDetectorRef,
    private platform: Platform,
    public modalController: ModalController
  ) {
    // 清除订阅
    this.eventService.eventEmit.on("clearInformationHallSubscription", (obj) => {
      const reqTag = localStorage.getItem('clearInformationHallSubscriptionTag');
      localStorage.removeItem('clearInformationHallSubscriptionTag');
      if (reqTag !== undefined) {
        try {
          console.log('msg----->clear ... ');
          this.subscription.unsubscribe();
        } catch (error) {
          console.log('error----->' + JSON.stringify(error));
        }
      }
    });
  }

  ngOnInit() {

    const listenerName = this.tagData.name + 'AskForList';
    this.eventService.eventEmit.on(listenerName, (obj) => {
      this.refreshListData(obj);
    });

    this.params = this.tagData.data.submit;

    if (this.tagData && this.tagData.hint) {
      this.emptyDataHint = this.tagData.hint;
    }

    if (!this.subscription && this.tagData.data.submit !== undefined) {
      if (
        this.tagData.data.submit.content &&
        this.tagData.data.submit.content.showName
      ) {
        sessionStorage.setItem(
          "showName",
          this.tagData.data.submit.content.showName
        );
      } else {
        sessionStorage.removeItem("showName");
      }




      // // 自己添加demo数据
      // console.log('data list = ' + this.tagData.data.data);
      // const demoArray = this.tagData.data.data;

      // // tslint:disable-next-line:prefer-for-of
      // for (let index = 0; index < demoArray.length; index++) {
      //   const subject = demoArray[index];
      //   subject.shareRow = {
      //     data: [
      //       {
      //         shareIcon: "/assets/laijian/share_icon_qq@3x.png",
      //         imageUrl: "http://sz.pupuwang.com/img/logo.fa4183f9.png",
      //         label: "QQ",
      //         title: "罗湖区国贸123㎡餐馆转让",
      //         // tslint:disable-next-line:max-line-length
      //         webpageUrl: "https://m.laijian100.com/#/home/tab1/details?params=%7B%22plugin_id%22%3A%221%22%2C%22opportunity_id%22%3A%225ff7fca416fc3c00013e6b20%22%2C%22type%22%3A%22lj_opp%22%7D",
      //         content: "123平米，租金：元/月，23142323"
      //       }
      //       ,
      //       {
      //         shareIcon: "/assets/laijian/share_icon_WeChat@3x.png",
      //         imageUrl: "http://sz.pupuwang.com/img/logo.fa4183f9.png",
      //         label: "weixin",
      //         title: "罗湖区国贸123㎡餐馆转让",
      //         // tslint:disable-next-line:max-line-length
      //         webpageUrl: "https://m.laijian100.com/#/home/tab1/details?params=%7B%22plugin_id%22%3A%221%22%2C%22opportunity_id%22%3A%225ff7fca416fc3c00013e6b20%22%2C%22type%22%3A%22lj_opp%22%7D",
      //         content: "123平米，租金：元/月，23142323"
      //       },
      //       {
      //         shareIcon: "/assets/laijian/share_icon_douyin@3x.png",
      //         imageUrl: "http://sz.pupuwang.com/img/logo.fa4183f9.png",
      //         label: "douyin",
      //         title: "罗湖区国贸123㎡餐馆转让",
      //         // tslint:disable-next-line:max-line-length
      //         webpageUrl: "https://m.laijian100.com/#/home/tab1/details?params=%7B%22plugin_id%22%3A%221%22%2C%22opportunity_id%22%3A%225ff7fca416fc3c00013e6b20%22%2C%22type%22%3A%22lj_opp%22%7D",
      //         content: "123平米，租金：元/月，23142323"
      //       },
      //       {
      //         shareIcon: "/assets/laijian/share_icon_58@3x.png",
      //         imageUrl: "http://sz.pupuwang.com/img/logo.fa4183f9.png",
      //         label: "58",
      //         title: "罗湖区国贸123㎡餐馆转让",
      //         // tslint:disable-next-line:max-line-length
      //         webpageUrl: "https://m.laijian100.com/#/home/tab1/details?params=%7B%22plugin_id%22%3A%221%22%2C%22opportunity_id%22%3A%225ff7fca416fc3c00013e6b20%22%2C%22type%22%3A%22lj_opp%22%7D",
      //         content: "123平米，租金：元/月，23142323"
      //       }, {
      //         shareIcon: "/assets/laijian/share_icon_Wechat Moments@3x.png",
      //         imageUrl: "http://sz.pupuwang.com/img/logo.fa4183f9.png",
      //         label: "moment",
      //         title: "罗湖区国贸123㎡餐馆转让",
      //         // tslint:disable-next-line:max-line-length
      //         webpageUrl: "https://m.laijian100.com/#/home/tab1/details?params=%7B%22plugin_id%22%3A%221%22%2C%22opportunity_id%22%3A%225ff7fca416fc3c00013e6b20%22%2C%22type%22%3A%22lj_opp%22%7D",
      //         content: "123平米，租金：元/月，23142323"
      //       },
      //       {
      //         shareIcon: "/assets/laijian/share_icon_save_pictures@3x.png",
      //         imageUrl: "http://sz.pupuwang.com/img/logo.fa4183f9.png",
      //         label: "savePic",
      //         title: "罗湖区国贸123㎡餐馆转让",
      //         // tslint:disable-next-line:max-line-length
      //         webpageUrl: "https://m.laijian100.com/#/home/tab1/details?params=%7B%22plugin_id%22%3A%221%22%2C%22opportunity_id%22%3A%225ff7fca416fc3c00013e6b20%22%2C%22type%22%3A%22lj_opp%22%7D",
      //         content: "123平米，租金：元/月，23142323"
      //       }
      //     ],
      //     maxIcon: "5",
      //     iconList: {
      //       shareBtn: {
      //         iconName: "../../../assets/img/list_share@3x.png",
      //         fieldLinkType: {
      //           link: {
      //             type: "page",
      //             params: {
      //               plugin_id: "1",
      //               opportunity_id: "5ff7fca416fc3c00013e6b20"
      //             },
      //             target: 206213
      //           }
      //         },
      //         modelType: "iconLink",
      //         label: "分享"
      //       }
      //     }
      //   };
      //   this.tagData.data.data[index] = subject;
      // }
      // event.target.disabled = true;
      this.message.clearMessage();
      this.pageNo = 1;
      this.params.sessionId = localStorage.getItem("sessionId");

      this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize));
      // 获取筛选参数
      this.subscription = this.message.getMessage().subscribe(param => {

        if (param === undefined) {
          return;
        } else if (param.type === 'ionRefresh') {
          this.refreshData(param);
          return;
        }

        // 参数
        this.params.content = param;
        // 页面数据参数
        this.params.content.pageNo = this.pageNo;
        // 请求获取新数据
        this.httpService.post(
          "application/submit",
          this.params,
          res => {
            console.log("submit");
            // 请求数据成功
            if (res.success) {
              const result = res.data.data;
              // 筛选数据
              this.tagData.data.data = result;
              this.cssStyle();
              // 自动回到顶部
              setTimeout(() => {
                const el = document.getElementById('information0');
                if (el) {
                  el.scrollIntoView(true);
                }

              }, 200);
            } else {
              // 请求数据失败
              this.appGlobalService.showToast(res.message, 2000, "middle");
            }
          },
          err => {
            // 请求数据失败
            this.appGlobalService.showToast(err.message, 2000, "middle");
          }
        );
      });
    }
    this.cssStyle();
    // tslint:disable-next-line:prefer-for-of
  }

  refreshListData(param) {
    const that = this;
    if (param === undefined) {
      return;
    }
    this.pageNo = 1;
    if (!param.showName) {
      if (this.tagData.data.moreButton && this.tagData.data.moreButton.link.params.showName) {
        param.showName = this.tagData.data.moreButton.link.params.showName;
      } else if (this.tagData.data.submit && this.tagData.data.submit.content.showName) {
        param.showName = this.tagData.data.submit.content.showName;
      }
    }
    that.params.content = param;
    that.params.content.pageNo = this.pageNo;
    that.params.sessionId = localStorage.getItem('sessionId');
    this.httpService.post('application/submit', that.params, res => {
      if (res.success) {
        this.tagData.data.data = [];
        // const result = res.data.data; // JSON.parse(res.data.data);
        // this.listData = res.data.data;
        if (res.data.submit) {
          this.params = res.data.submit; // 为了每次刷新下一页的参数 "oldIndex"
        }

        this.tagData.data.data = res.data.data;

        if (res.data.moreButton) {
          this.tagData.data.moreButton = res.data.moreButton;
        }
        this.pageTotal = this.tagData.pageTotal;

        // tslint:disable-next-line:max-line-length
        this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize)) && this.tagData.asyncShow !== 'true';
      } else {
        // 请求数据失败
        this.tagData.data.data = [];
        this.appGlobalService.showToast(res.message, 2000, 'middle');
      }
    },
      err => {
        // 请求数据失败
        this.tagData.data.data = [];
        this.appGlobalService.showToast(err.message, 2000, 'middle');
      });
  }

  /**
   *
   * @param item 渲染页面按钮样式
   * @param dataIndex
   */
  cssStyle() {
    if (this.tagData.data && this.tagData.data.data) {
      this.tagData.data.data.forEach(data => {
        if (
          data.fourthRowLeft && data.fourthRowLeft.firstText &&
          data.fourthRowLeft.firstText.cssStyle
        ) {
          const cssStyles = data.fourthRowLeft.firstText.cssStyle.split(";");
          const childCss = {};
          // tslint:disable-next-line:prefer-for-of
          for (let i = 0; i < cssStyles.length; i++) {
            const cssStrs = cssStyles[i].split(":");
            childCss[cssStrs[0]] = cssStrs[1];
          }
          data.fourthRowLeft.firstText.childCss = childCss;
        }
        if (
          data.fourthRowLeft && data.fourthRowLeft.secondTag &&
          data.fourthRowLeft.secondTag.cssStyle
        ) {
          const cssStyles = data.fourthRowLeft.secondTag.cssStyle.split(";");
          const childCss = {};
          // tslint:disable-next-line:prefer-for-of
          for (let i = 0; i < cssStyles.length; i++) {
            const cssStrs = cssStyles[i].split(":");
            childCss[cssStrs[0]] = cssStrs[1];
          }
          data.fourthRowLeft.secondTag.childCss = childCss;
        }
        if (data.fourthRowLeft && data.fourthRowLeft.firstTag && data.fourthRowLeft.firstTag.cssStyle) {
          const cssStyles = data.fourthRowLeft.firstTag.cssStyle.split(";");
          const childCss = {};
          // tslint:disable-next-line:prefer-for-of
          for (let i = 0; i < cssStyles.length; i++) {
            // tslint:disable-next-line:prefer-const
            const cssStrs = cssStyles[i].split(":");
            childCss[cssStrs[0]] = cssStrs[1];
          }
          data.fourthRowLeft.firstTag.childCss = childCss;
        }
        if (
          data.fourthRowLeft && data.fourthRowLeft.secondTest &&
          data.fourthRowLeft.secondTest.cssStyle
        ) {
          const cssStyles = data.fourthRowLeft.secondTest.cssStyle.split(";");
          const childCss = {};
          // tslint:disable-next-line:prefer-for-of
          for (let i = 0; i < cssStyles.length; i++) {
            // tslint:disable-next-line:prefer-const
            const cssStrs = cssStyles[i].split(":");
            childCss[cssStrs[0]] = cssStrs[1];
          }
          data.fourthRowLeft.secondTest.childCss = childCss;
        }
      });
    }

  }

  /**
   *
   * @param item 打开图标
   */
  openIcon(item, dataIndex?, maxIconList?) {
    if (maxIconList && maxIconList === '2') {
      this.icons = item.slice(1);
    } else {
      this.icons = item.slice(2);
    }

    this.showActionSheet(this.icons);
    // this.openInformation = true;
    this.dataIndex = dataIndex;
  }

  /**
   * 关闭图标
   */
  hiddenInformation() {
    this.openInformation = false;
    this.openRemarks = false;
  }

  // 分享弹框
  async presentShareModal(shareData) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'sharePage',
      backdropDismiss: true,
      component: SharePageComponent,
      componentProps: { tagData: shareData }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    // console.log(modalData);
  }


  // 分享弹框
  async presentShare58Modal(shareData) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'recommend-modal',
      backdropDismiss: true,
      component: ShareFormModalComponent,
      componentProps: { tagData: shareData }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    // console.log(modalData);
  }

  // 蜂喔商户1.6.15 点击事件重叠
  newIconClick(item, event) {
    event.stopPropagation();
    this.iconClick(item);
  }

  /**
   *
   * @param item 点击图标
   */
  iconClick(item, dataIndex?) {
    if (item.link && item.link.type === 'model') {
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: item.link.target,
        params: item.link.params
      };
      this.httpService.post('application/page', params, async res => {
        const modal = await this.modalController.create({
          showBackdrop: true,
          cssClass: item.link.params.modelCss,
          component: NestedFormTagComponent,
          componentProps: { pageData: JSON.parse(res.script), cssClass: item.link.params.modelCss, cssStyle: item.link.params.cssStyle }
        });
        await modal.present();
        const modalData = await modal.onDidDismiss().then((data) => {
          if (item.link.params.deleteAfterSubmit !== undefined
            && (data.data.data === true || data.data === 'success')
            && dataIndex !== undefined) {
            this.sliceData(dataIndex);
          }
        });
      });
    } else if (item.link && item.link.type === 'page') {
      const params = {
        pageId: item.link.target,
        params: item.link.params,
        sessionId: localStorage.getItem("sessionId")
      };
      this.appGlobalService.goToForward(params);
      return;
    } else if (item.action === 'question') {
      this.question(item.button, item.label, item.operation, dataIndex);
    }
    if (dataIndex >= 0) {
      this.dataIndex = dataIndex;
    }
    this.hiddenInformation();
    // console.log(item);
    if (item.modelType === "iconLink") {
      if (item.link.type && item.link.type === 'chat') {//
        this.httpService.gotoChat(item);
      } else if (item.label === '分享') {
        const params = {
          sessionId: localStorage.getItem("sessionId"),
          pageId: item.link.target,
          params: item.link.params
        };
        this.httpService.post('application/page', params, res => {
          console.log(JSON.parse(res.script));
          const tmpShareData = JSON.parse(res.script).views[0].tags[0].data;
          // console.log(tmpShareData);
          this.presentShareModal(tmpShareData);
        });
      } else {
        // 修改
        const params = {
          pageId: item.link.target,
          params: item.link.params,
          sessionId: localStorage.getItem("sessionId")
        };
        this.appGlobalService.goToForward(params);
      }
    }
    if (item.modelType === "iconSubmit") {


      let tmpSubmit;

      if (item.button && item.button.submit) {
        tmpSubmit = item.button.submit;
      } else {
        tmpSubmit = item.submit;
      }

      // 领取
      const params = {
        content: tmpSubmit.content,
        id: tmpSubmit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          this.appGlobalService.reloadCurrentPage();
          if (item.link && item.link.target) {
            const pageParams = {
              pageId: item.link.target,
              params: item.link.params ? item.link.params : {},
              sessionId: localStorage.getItem("sessionId")
            };
            this.appGlobalService.goToForward(pageParams);
          }
        }
      });
    }

    if (item.modelType === 'iconDelete') {
      // 删除
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (this.dataIndex >= 0 && this.dataIndex < this.tagData.data.data.length) {
            this.tagData.data.data.splice(this.dataIndex, 1);
          }
        }
      });
    }
    if (item.modelType === "phone") {
      // 电话
      this.phoneArray = item.phone.split(",");
      if (this.phoneArray.length > 1) {
        this.presentAction();
      } else {
        this.presentAlertConfirm(Number(this.phoneArray[0]), item.label);
      }
    }
    if (item.modelType === "dialog") {
      // 备注
      // this.remarksIcon = item;
      // this.openRemarks = true;
      this.presentModal("remarks", item);
    }
    // 商铺列表新增类型
    if (item.modelType === 'pageDialog') {
      this.openTipsPageModal("recommend-modal", item);
    }
    // 新增两个components类型
    if (item.modelType === "remarkList") {
      // tslint:disable-next-line:max-line-length
      // const moreObj = JSON.parse('{"layout":"right","data":[{"submit":{"id":"refresh","content":{"opportunity_id":"5eb3aed42872fb0001f76ed7"}},"action":"submit","label":"刷新","paramName":"opportunity_id"},{"link":{"type":"page","params":{"opportunity_id":"5eb3aed42872fb0001f76ed7"},"target":144348},"action":"link","label":"修改"}],"icon":"nav_icon_more@3x.png"}');
      if (item.listRemark) {
        this.remarkList(item);
      }
    }
    if (item.modelType === "serviceModal") {
      this.openSeviceModal("sevice-modal", item);
    }
    if (item.modelType === "childIconLink") {
      if (item.childIconList) {
        this.remarkList(item);
      }
    }
  }

  sliceData(dataIndex) {
    const tempArry = [];
    for (let index = 0; index < this.tagData.data.data.length; index++) {
      if (dataIndex !== index) {
        const element = this.tagData.data.data[index];
        tempArry.push(element);
      }
    }
    this.tagData.data.data = tempArry;
  }

  async question(item, msg, operation?, dataIndex?) {
    // 蜂喔商户1.6.18 新增如果消息内容为空则直接提交submit
    if (msg === '') {
      if (item.submit) {
        const params = {
          content: item.submit.content,
          id: item.submit.id,
          sessionId: localStorage.getItem("sessionId")
        };
        this.httpService.post("application/submit", params, res => {
          this.appGlobalService.showToast(res.message, 1500, "middle");
          if (res.success) {
            this.appGlobalService.reloadCurrentPage();
          }
        });
      }
    } else {
      const alert = await this.alertController.create({
        header: '',
        subHeader: '',
        message: msg,
        buttons: [{
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary',
          handler: (blah) => {
            console.log('取消');
          }
        }, {
          text: '确定',
          cssClass: 'LJ',
          handler: () => {
            if (item.submit) {
              const params = {
                content: item.submit.content,
                id: item.submit.id,
                sessionId: localStorage.getItem("sessionId")
              };
              this.httpService.post("application/submit", params, res => {
                this.appGlobalService.showToast(res.message, 1500, "middle");
                if (res.success) {
                  this.appGlobalService.reloadCurrentPage();
                }
              });
            } else if (item.link) {
              const param = {
                pageId: item.link.target,
                params: item.link.params ? item.link.params : {},
                sessionId: localStorage.getItem('sessionId')
              };
              item.disabled = false;
              this.appGlobalService.goToForward(param);
            }

            if (operation) {
              this.changeSort(dataIndex, operation === 'up' ? 0 : 1);
            }
          }
        }]
      });
      await alert.present();
    }


  }

  async openSeviceModal(className, item) {
    const type = {
      "sevice-modal": ServiceModuleComponent,
    };
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: className,
      component: type[className],
      componentProps: { tagData: item }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
  }

  remarkList(more) {
    const that = this;
    const buttons: any = [];
    if (more.childIconList) {
      more.listRemark = more.childIconList;
    }
    more.listRemark.forEach((element, index) => {
      buttons.push(element.label);
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex > -1) {
          console.log(more.listRemark[buttonIndex]);
          ActionSheetService.close();
          setTimeout(() => {
            that.selectItem(more, buttonIndex);
          }, 200);
        }
      }
    );



  }

  selectItem(item, index) {
    const itemObj = item.listRemark[index];
    if (itemObj.modelType === 'dialog') {
      this.presentModal("remarks", itemObj);
    } else if (itemObj.modelType === 'pageDialog') {
      this.openTipsPageModal("recommend-modal", itemObj);
    } else if (itemObj.modelType === 'iconLink') {
      // 修改 领取类型按钮
      const params = {
        pageId: itemObj.link.target,
        params: itemObj.link.params,
        sessionId: localStorage.getItem("sessionId")
      };
      this.appGlobalService.goToForward(params);
    } else if (itemObj.modelType === 'phone') {
      // 电话
      this.phoneArray = itemObj.phone.split(",");
      if (this.phoneArray.length > 1) {
        this.presentAction();
      } else {
        this.presentAlertConfirm(Number(this.phoneArray[0]), itemObj.label);
      }
    } else if (itemObj.modelType === 'iconSubmit') {
      // 领取
      const params = {
        content: itemObj.submit.content,
        id: itemObj.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (itemObj.link.target) {
            const pageParams = {
              pageId: itemObj.link.target,
              params: itemObj.link.params ? itemObj.link.params : {},
              sessionId: localStorage.getItem("sessionId")
            };
            this.appGlobalService.goToForward(pageParams);
          }
        }
      });
    } else if (itemObj.modelType === 'iconDelete') {
      // 删除
      const params = {
        content: itemObj.submit.content,
        id: itemObj.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (this.dataIndex >= 0 && this.dataIndex < this.tagData.data.data.length) {
            this.tagData.data.data.splice(this.dataIndex, 1);
          }
        }
      });
    }
  }


  showActionSheet(icons) {
    const that = this;
    const buttons: any = [];
    icons.forEach((element, index) => {
      buttons.push(element.label);
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex > -1) {
          console.log(icons[buttonIndex]);
          ActionSheetService.close();
          setTimeout(() => {
            that.iconClick(icons[buttonIndex]);
          }, 200);
        }
      }
    );
  }

  async presentModal(value, item) {
    console.log("item", item);
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: value,
      component: RemarksContentComponent,
      componentProps: { item, type: value }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData, "moddddddd");
  }

  async presentAction() {
    const buttonsArr = [
      {
        text: "取消",
        cssClass: ["action-sheet-font-color", "action-sheet-font-top"],
        handler: () => {
          actionSheet.dismiss();
        }
      }
    ];
    if (this.phoneArray[1]) {
      buttonsArr.unshift({
        text: this.phoneArray[1],
        cssClass: ["action-sheet-font-color"],
        handler: () => {
          this.presentAlertConfirm(Number(this.phoneArray[1]));
        }
      });
    }

    if (this.phoneArray[0]) {
      buttonsArr.unshift({
        text: this.phoneArray[0],
        cssClass: ["action-sheet-font-color"],
        handler: () => {
          this.presentAlertConfirm(this.phoneArray[0]);
        }
      });
    }

    const actionSheet = await this.actionSheetCtrl.create({
      mode: "md",
      cssClass: "match-padding",
      buttons: buttonsArr
    });
    await actionSheet.present();
  }

  async presentAlertConfirm(mobile, name?) {
    const msg = (name ? name + ' ' : '') + mobile;
    const alert = await this.alertController.create({
      header: this.tagData.nickName,
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "拨打",
          handler: () => {
            this.httpService.changeCallNumber(mobile);
          }
        }
      ]
    });

    await alert.present();
  }

  /**
   * 提交备注
   */
  submitRemarks() {
    if (this.remarksText === "") {
      this.appGlobalService.showToast("请填写备注", 1000, "top");
      return;
    }
    const contentArray = this.remarksIcon.formData.button.submit.content;
    // tslint:disable-next-line:no-string-literal
    contentArray["remark_text"] = this.remarksText;
    const params = {
      content: contentArray,
      id: this.remarksIcon.formData.button.submit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.post("application/submit", params, res => {
      if (res.success) {
        this.remarksText = "";
        this.openRemarks = false;
        this.appGlobalService.showToast(res.message, 1000, "bottom");
      } else {
        this.appGlobalService.showToast(res.message, 1000, "bottom");
      }
    });
  }

  go(item,index) {
    if(item.link && item.link.params && item.link.params.currentIndex){
      item.link.params.currentIndex = index;
    }
    this.pageModalService.openPage(item.link, item.title);
  }

  pullToRefresh() {

  }
  refreshData(event?) {
    this.params.sessionId = localStorage.getItem("sessionId");
    // 请求下一个页面
    this.pageNo = 1;
    this.params.content.pageNo = this.pageNo;
    // 请求获取新数据
    this.httpService.post("application/submit", this.params, res => {
      // 请求数据成功
      if (res.success) {

        if (Array.isArray(res.data.data) && res.data.data.length > 0) {
          this.tagData.data.data = res.data.data;
          this.cssStyle();

          // this.params = res.data.submit;
        } else {
          this.tagData.data.data = [];
          // 没有数据了
          // this.appGlobalService.showToast("没有数据了...", 1000, "bottom");
        }
        if (event) {
          event.target.complete();
        }

      } else {
        // 请求失败，更新当前页数
        this.tagData.data.data = [];
        this.pageNo = 1;
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, "middle");
        if (event) {
          event.target.complete();
        }
      }
    });
  }

  loadData(event) {
    setTimeout(() => {
      this.params.sessionId = localStorage.getItem("sessionId");
      // 请求下一个页面
      this.pageNo = this.pageNo + 1;
      this.params.content.pageNo = this.pageNo;
      // 请求获取新数据
      this.httpService.post("application/submit", this.params, res => {
        // 请求数据成功
        if (res.success) {
          // 追加返回数据
          if (Array.isArray(res.data.data) && res.data.data.length > 0) {
            // 追加数据
            res.data.data.map(item => {
              this.tagData.data.data.push(item);
              this.cssStyle();
            });
            // this.params = res.data.submit;
          } else {
            // 没有数据了
            // this.appGlobalService.showToast("没有数据了...", 1000, "bottom");
          }
          event.target.complete();
        } else {
          // 请求失败，更新当前页数
          this.pageNo = this.pageNo - 1;
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, "middle");
          event.target.complete();
        }
      });
    }, 500);
  }

  openModalLink(item, label) {
    try {
      if (label === '业务中' || label === '签约中') {
        if (item && item.type === 'modal') {
          this.openNewBusinessInfoModal("recommend-modal", item);
        }
      } else {
        return;
      }

    } catch (error) {
    }
  }

  async openNewBusinessInfoModal(className, item: any) {
    try {
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: item.target,
        params: item.params
      };
      this.httpService.post('application/page', params, async res => {
        const tagData = JSON.parse(res.script).views[0].tags[0].data;
        if (tagData.data && tagData.data.length > 0) {
          const modal = await this.modalController.create({
            showBackdrop: true,
            cssClass: className,
            animated: false,
            component: NewBusinessInfoModalComponent,
            componentProps: { tagData }
          });
          await modal.present();
          // 监听销毁的事件
          const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
        }
      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }

  }

  async openTipsPageModal(className, item: any) {
    try {
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: item.link.target,
        params: item.link.params
      };
      this.httpService.post('application/page', params, async res => {
        const tagData = JSON.parse(res.script).views[0].tags[0].data;
        if (tagData) {
          const modal = await this.modalController.create({
            showBackdrop: true,
            cssClass: className,
            animated: false,
            component: RecommendModalComponent,
            componentProps: { tagData },
            leaveAnimation: ModalFromCenterLeave,
            enterAnimation: ModalFromCenterEnter
          });
          await modal.present();
          const modalData = await modal.onDidDismiss().then((data) => {
            this.appGlobalService.reloadCurrentPage();
          }); // 获取关闭传回的值
        }
      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }



  // async openTipsPageModal(className, item: any) {
  //   try {
  //     const params = {
  //       sessionId: localStorage.getItem("sessionId"),
  //       pageId: item.target,
  //       params: item.params
  //     };
  //     this.httpService.post('application/page', params, async res => {
  //       const tagData = JSON.parse(res.script).views[0].tags[0].data;
  //       if (tagData.data && tagData.data.length > 0) {
  //         const modal = await this.modalController.create({
  //           showBackdrop: true,
  //           cssClass: className,
  //           animated: false,
  //           component: RecommendModalComponent,
  //           componentProps: { tagData }
  //         });
  //         await modal.present();
  //         // 监听销毁的事件
  //         const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
  //       }
  //     });
  //   } catch (error) {
  //     console.log('error----->' + JSON.stringify(error));
  //   }
  // }

  gotoSharePage(obj) {
    if (obj.tips) {
      this.appGlobalService.showToast(obj.tips, 2000, "middle");
      return;
    }
    if (obj && obj.label) {
      switch (obj.label) {
        case 'qq':
          this.shareService.shareQQ(obj.title, obj.content, obj.imageUrl, obj.webpageUrl);
          break;
        case 'qzone':
          this.shareService.shareQQZone(obj.title, obj.content, obj.imageUrl, obj.webpageUrl);
          break;
        case 'wechat':
          this.shareService.shareWeiXin(obj.title, obj.content, obj.imageUrl, obj.webpageUrl);
          break;
        case 'moment':
          this.shareService.shareMoments(obj.title, obj.content, obj.imageUrl, obj.webpageUrl);
          break;
        case '58':
          this.shareService.share58(obj);
          break;
        case 'tikTok': // 抖音
          if (obj.isInValidImgPosterSharing) {
            // 脚本配置 <dataItem name="isInValidImgPosterSharing" value="true"/>
            // 用于新增需求 求租求购，找店、找写字楼、找厂房等：没有图片或信息本身任何图片，生成画报，分享画报图片
            this.shareService.shareDouyinForInValidImg(obj.link.fieldLinkType);
          } else {
            this.shareService.shareDouyin(obj.title, obj.content, obj.imageUrls, obj.webpageUrl, obj.shareType);
          }
          break;
        case 'kwai': // 快手 https://play.google.com/store/apps/details?id=com.kwai.video&hl=zh&gl=US
          this.shareService.shareKuaishou(obj.title, obj.content, obj.imageUrl, obj.webpageUrl, obj.shareType);
          break;
        case 'copy':
          this.shareService.copyUrl(obj.webpageUrl);
          break;
        case 'savePic':
          // this.shareService.savePic();
          break;
        case 'posterSharing':
          this.shareService.posterSharing(obj.link.fieldLinkType);
          break;
        default:
          console.log('...gotoSharePage');
          break;
      }

    }
  }

  openShareModal(obj) {
    if (obj) {
      let subject = obj;
      if (obj.shareBtn && obj.shareBtn.fieldLinkType) {
        subject = obj.shareBtn.fieldLinkType;
      }
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: subject.link.target,
        params: subject.link.params
      };
      this.httpService.post('application/page', params, res => {
        console.log(JSON.parse(res.script));
        const tmpShareData = JSON.parse(res.script).views[0].tags[0].data;
        this.presentShareModal(tmpShareData);
      });
    }
  }

  async previewImage(event, imageUrl, tmpIndex, isPreview,dataIndex) {
    event.stopPropagation();
    if (isPreview && isPreview !== undefined) {
      // const that = this;
      let tempImageUrl = 'assets/img/default_img.png';
      if (imageUrl !== undefined) {
        if (imageUrl.imgLink) {
          imageUrl.imgLink.link.modalCss = 'video-modal';
          if(imageUrl.imgLink.link && imageUrl.imgLink.link.params && imageUrl.imgLink.link.params.currentIndex){
            imageUrl.imgLink.link.params.currentIndex = dataIndex; // 跳转播放指定位置视频
          }
          this.pageModalService.openPage(imageUrl.imgLink.link);
          return;
        }
        tempImageUrl = imageUrl;
      }
      const value = { img: [tempImageUrl], index: tmpIndex };
      const modal = await this.modalController.create({
        component: ImgSlidePage,
        componentProps: { value: JSON.stringify(value) }
      });
      return await modal.present();
    }
  }
  gotoChat(e, customerUserId, customerNickName, oppDetail) {
    e.stopPropagation();

    try {
      const nowDate = Date.now();
      const shareFromUserId = localStorage.getItem("connUserId");
      const message = {
        text: oppDetail.title,
        toId: customerUserId,
        fromId: shareFromUserId,
        toUserName: customerNickName,
        toUserId: customerUserId,
        key: customerUserId + '-' + shareFromUserId,
        type: 'opp',
        opportunity_id: oppDetail.opportunity_id,
        title: oppDetail.title,
        imags: oppDetail.imags ? oppDetail.imags : '../../../assets/img/375x250@2x.png',
        pluginId: oppDetail.pluginId,
        big_district: oppDetail.big_district ? oppDetail.big_district : '',
        district: oppDetail.district ? oppDetail.district : '',
        area: oppDetail.area ? oppDetail.area : '',
        industry: oppDetail.industry ? oppDetail.industry : '',
        rent: oppDetail.rent ? oppDetail.rent : '',
        transfer_fee: oppDetail.transfer_fee ? oppDetail.transfer_fee : '',
        nowDate
      };
      localStorage.setItem('onSendWebSocketMessageTag', 'true');
      this.eventService.eventEmit.emit("onSendWebSocketMessage", message);
      this.appGlobalService.showToast('发送成功', 2000, 'middle');

      setTimeout(() => {
        const item = { link: { params: { opportunity_id: undefined, customer_id: undefined } }, nickname: customerNickName };
        this.httpService.gotoChat(item, customerUserId);
      }, 2000);

    } catch (error) {

    }
  }
  ngOnDestroy(): void {
    this.eventService.removeCustomListListenersByName(this.tagData.name + 'AskForList');
    this.subscription.unsubscribe();
  }

  morebtnClick(moreLink, index) {
    if (!moreLink) {
      return;
    }
    this.showActionSheet(moreLink);
  }
  normalBtnClick(buttonItem, dataIndex?) {
    if (!buttonItem) {
      return;
    }
    this.iconClick(buttonItem, dataIndex);
  }
  copyStr(e, str) {
    e.stopPropagation();
    this.appGlobalService.copyString(str,'手机号码');
  }

  /*
  * 上移 type 为 0， 下移为 1.
  * index 为 当前移动元素的下标
  */
  changeSort(index, type) {
    let index1 = index;
    let index2 = index;
    if (type == 0) {
      if (index - 1 < 0) {
        return;
      }
      index2 = index - 1;
    } else if (type === 1) {
      if (index + 1 >= this.tagData.data.data.length) {
        return;
      }
      index2 = index + 1;

    }
    const arr = this.tagData.data.data;
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
    return arr;
    // this.tagData.data.data.splice(type ? index : index - 1, 1,
    //   ...this.tagData.data.data.splice(type ? index + 1 : index, 1, this.tagData.data.data[type ? index : index - 1]));
  };

  changeSort2(arr, index1, index2) {
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
    return arr;
  };

  async watchVideo(event, videoUrl, type) {
    event.stopPropagation();
    if (videoUrl && type !== undefined) {
      let data = [];
      data['videoUrl'] = [videoUrl];
      const modal = await this.modalController.create({
        component: VideoImgPopupComponent,
        componentProps: { tagData: data }
      });
      return await modal.present();
    }
  }

}
